package com.lc.alipay.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lc.alipay.config.AliPayConfig;
import com.study.common.utils.NoUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/4 11:28
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {


    @GetMapping("/showPay")
    public void showPay(HttpServletRequest request, HttpServletResponse response) throws Exception {

        DefaultAlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL, AliPayConfig.APPID, AliPayConfig.MERCHANT_PRIVATE_KEY,
                                                            "json", AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig.RETURN_URL);
        alipayRequest.setNotifyUrl(AliPayConfig.NOTIFY_URL);

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String outTradeNo = NoUtil.create();
        // 付款金额，必填
        String totalAmount = "1";
        // 订单名称，必填
        String subject = "测试订单";
        // 商品描述，选填
        String body = "测试商品描述";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", outTradeNo);
        jsonObject.put("total_amount", totalAmount);
        jsonObject.put("subject", subject);
        jsonObject.put("body", body);
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(jsonObject.toJSONString());

        String top = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
                "<title>付款</title>\n" +
                "</head>";
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        String bottom = "<body>\n" +
                "</body>\n" +
                "</html>";
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(top.concat(result).concat(bottom));
    }

}
